<template>
  <el-button-group v-bind="$attrs">
    <slot name="before"></slot>

    <el-button
      v-for="button in mergedButtons"
      :key="button.action"
      :type="button.type"
      :size="button.size"
      :icon="button.icon"
      :loading="button.loading"
      :disabled="button.disabled"
      @click="handleClick(button.action)"
    >
      {{ button.text }}
    </el-button>

    <slot name="after"></slot>
  </el-button-group>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ElButton, ElButtonGroup } from 'element-plus'

// 类型定义
type ButtonType = '' | 'primary' | 'success' | 'warning' | 'danger' | 'info'
type ButtonSize = 'large' | 'default' | 'small'
type DefaultButton = 'edit' | 'delete' | 'view'

// 基础按钮配置
interface Button {
  type: ButtonType
  text: string
  action: string
  size?: ButtonSize
  icon?: string
  loading?: boolean
  disabled?: boolean
}

interface Props {
  buttons?: Button[]
  defaultButtons?: DefaultButton[]
  rowData?: any
}

const props = withDefaults(defineProps<Props>(), {
  buttons: () => [],
  defaultButtons: () => [],
  rowData: () => ({}),
})

  const emit = defineEmits<{
    (e: 'action', action: string, data?: any): void
  }>()

  const defaultButtonConfig: Record<string, Omit<Button, 'action'>> = {
    edit: {
      type: 'primary',
      text: '编辑',
      size: 'small',
    },
    delete: {
      type: 'danger',
      text: '删除',
      size: 'small',
    },
    view: {
      type: 'info',
      text: '查看',
      size: 'small',
    },
  }

  const mergedButtons = computed(() => {
    // 合并默认按钮和自定义按钮
    const buttons: Button[] = []

    // 添加默认按钮
    props.defaultButtons.forEach(action => {
      if (defaultButtonConfig[action]) {
        buttons.push({
          ...defaultButtonConfig[action],
          action,
        } as Button)
      }
    })

    // 添加自定义按钮
    props.buttons.forEach(button => {
      buttons.push(button)
    })

    return buttons
  })

  const handleClick = (action: string) => {
    emit('action', action, props.rowData)
  }
</script>
